function [ gf2 ] = addRemain( grains, ng, ORmat, gf1, opp1, n, w )
% Add remaining orientation to the closest fragment
%
% Syntax
%   [ gf2 ] = addRemain( grains, ng, ORmat, gf1, opp1, n, w )
%
% Output
%   gf2     - new index of grain in fragments
%
% Input
%   grains  - grains map
%   ng      - number of grains
%   ORmat   - orientation matrix (alpha to gamma)
%   gf1     - index of grain in fragments
%   opp1    - parent orientation of fragments
%   n       - number of fragments
%   w       - tolerance angle
%
% History
% 12.04.13  Original implementation

%% Add remainnig grains
% Grains in fragments
prc = unique([gf1{:}]);

% Grains outside of all fragments
rmn = ones(1,ng);
rmn(prc) = 0;
rmn = find(rmn);

% Mean orientation of grains
o = get(grains, 'mean');

gf2 = gf1;
hn = length(rmn);
hi = 1; % process indicator

h = waitbar(0,'Add remain...');

% For all grains outside the fragments
for i = rmn
    % Check with all fragments
    [v, ~] = getVariants(o(i), ORmat, get(o,'CS'));
    for j = 1:n
        mm  = angle(v,opp1(j))';
        mml = mm < w;
        if (any(mml))
            gf2{j} = [gf2{j} i];
        end
    end
    hi = hi + 1;
    waitbar(hi/hn);
end
close(h);

prc = unique([gf2{:}]); % processed child index
rmn = ones(1,ng);       % remaining child index
rmn(prc) = 0; 
rmn = find(rmn);

if (~isempty(rmn))
    plotBoundary(grains,'ext'); hold on; plot(grains(rmn)); hold off;
end

end
